<template>
    <div class="scroll-wrapper">
        <div class="arrow l">
            <el-icon><ArrowLeft color="#777" @click="scrollLeft"/></el-icon>
        </div>
        
        <div class="scroll-container" ref="container">
            <div class="item-list" ref="list">
                <slot></slot>
            </div>
        </div>
        
        <div class="arrow r">
            <el-icon><ArrowRight color="#777" @click="scrollRight"/></el-icon>
        </div>
    </div>
</template>
  
<script setup>
import { ref, onMounted } from 'vue';
import {ArrowLeft, ArrowRight} from '@element-plus/icons-vue'

const container = ref(null);
const list = ref(null);

let scrollStep = 0;

const scrollLeft = () => {
    container.value.scrollTo({ left: container.value.scrollLeft - scrollStep, behavior: 'smooth' });
};

const scrollRight = () => {
    container.value.scrollTo({ left: container.value.scrollLeft + scrollStep, behavior: 'smooth' });
};

onMounted(() => {
    const containerWidth = container.value.offsetWidth;
    const listItemWidth = 200;
    const numVisibleItems = Math.floor(containerWidth / listItemWidth);
    scrollStep = numVisibleItems * listItemWidth;
    container.value.style.overflowX = 'hidden';
});

</script>
  
<style scoped>
.scroll-wrapper {
    display: flex;
    align-items: center;
    padding: 15px 0;
}

.scroll-button {
    width: 30px;
    height: 30px;
    font-size: 16px;
    border-radius: 50%;
    border:none;
    cursor: pointer;
}

.scroll-container {
    flex: 1;
    overflow: hidden;
    padding:0 10px;
}

.item-list {
    display: flex;
    list-style: none;
    padding: 0;
    margin: 0;
}

.item {
    flex: 0 0 auto;
    width: 200px;
    /* 为了演示方便，这里暂时写死每个商品的宽度 */
    height: 200px;
    background-color: #eee;
    margin-right: 10px;
}

.arrow{
    width: 40px;
    height: 40px;
    font-size: 30px;
    border-radius: 50%;
    cursor: pointer;
}

.l{
    margin-left: -40px;
}

.r{
    margin-right: -40px;
}
</style>
  